//
//  OneLevelLinkerCell.m
//  GC_OC
//
//  Created by tuibian  on 2022/5/26.
//

#import "OneLevelLinkerCell.h"
#import "LinkerCell.h"
#import <YYKit/YYKit.h>

@implementation OneLevelLinkerCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        self.backgroundColor = [UIColor clearColor];

        self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        self.tableView.backgroundColor = [UIColor clearColor];
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        self.tableView.dataSource = self;
        self.tableView.delegate = self;
        self.tableView.rowHeight = 40;
        [self.tableView registerClass:[LinkerCell class] forCellReuseIdentifier:@"LinkerCell"];
        [self.contentView addSubview:self.tableView];
        
        [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.contentView);
        }];
        
    }
    return self;
}

- (void)configCell:(NSMutableArray *)array {
    self.dataSource = array;
    [self.tableView reloadData];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return  self.dataSource.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    LinkerModel *info = self.dataSource[section];
    if ([info.isFold isEqual:@0] || self.isEditor == YES) {
        return 0;
    }
    NSMutableArray *array = info.list;
    return array.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    LinkerCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LinkerCell"];

    LinkerModel *info = self.dataSource[indexPath.section];
    NSMutableArray *array = info.list;

    [cell configCell:array[indexPath.row]];
    
    cell.aidvline.hidden = (indexPath.row == array.count - 1);

    cell.vline2.hidden = self.indexPath.section == self.fdataSource.count - 1;
    cell.vline3.hidden = (indexPath.section == self.dataSource.count - 1);

    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 38;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    LinkerModel *info = self.dataSource[section];
    NSString *name = info.name;
//    NSLog(@"🍎 2 name = %@", name);
    
    NSMutableArray *list = info.list;
    NSNumber *isSelect = info.isSelect;
    NSNumber *isFold = info.isFold;

    UIView *hView = [UIView new];
    hView.tag = 1000 + section;
    hView.backgroundColor = [UIColor clearColor];
    if ([isSelect isEqual:@1] && self.isEditor == NO) {
        hView.backgroundColor = XHUIColorFromRGBA(0x0091FF, 0.15);
    }

    UITapGestureRecognizer *hTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapHeaderView:)];
    [hView addGestureRecognizer:hTap];

    UIView *vline = [UIView new];
    vline.backgroundColor = XHUIColorFromRGB(0x979797);
    [hView addSubview:vline];

    UIView *aidvline = [UIView new];
    aidvline.backgroundColor = XHUIColorFromRGB(0x979797);
    [hView addSubview:aidvline];

    UIView *vline2 = [UIView new];
    vline2.backgroundColor = XHUIColorFromRGB(0x979797);
    [hView addSubview:vline2];

    UIView *aidvline2 = [UIView new];
    aidvline2.backgroundColor = XHUIColorFromRGB(0x979797);
    [hView addSubview:aidvline2];

    UIView *hline = [UIView new];
    hline.backgroundColor = XHUIColorFromRGB(0x979797);
    [hView addSubview:hline];

    NSString *str = name;
    NSString *nameStr2 = @"";
    if (list.count != 0) {
        str = [NSString stringWithFormat:@"%@[%ld]", name, list.count];
        nameStr2 = [NSString stringWithFormat:@"[%ld]", list.count];
    }

    //先查找分段样式文字的range
    NSRange range2 = [str rangeOfString:nameStr2];

    NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:str];

    //分段文字的颜色
    [attri addAttribute:NSForegroundColorAttributeName value:XHUIColorFromRGB(0x666666) range:range2];

    UILabel *hTitle = [UILabel new];
    if ([isSelect isEqual:@1] && self.isEditor == NO) {
        hTitle.textColor = XHUIColorFromRGB(0x0091FF);
    } else {
        hTitle.textColor = [UIColor blackColor];
    }
    hTitle.attributedText = attri;

    hTitle.font = [UIFont systemFontOfSize:16 weight:UIFontWeightRegular];
    if ([isSelect isEqual:@1]) {
        hTitle.font = [UIFont systemFontOfSize:16 weight:UIFontWeightSemibold];
    }
    [hView addSubview:hTitle];

    //添加
    UIButton *addButton = [UIButton new];
    [addButton setImage:[UIImage imageNamed:@"icon_返回_32_line备份_3"] forState:UIControlStateNormal];
    [addButton addTarget:self action:@selector(addAction:) forControlEvents:UIControlEventTouchUpInside];
    [hView addSubview:addButton];
    //删除
    UIButton *deleteButton = [UIButton new];
    [deleteButton setImage:[UIImage imageNamed:@"icon_返回_32_line备份_2"] forState:UIControlStateNormal];
    [deleteButton addTarget:self action:@selector(deleteAction:) forControlEvents:UIControlEventTouchUpInside];
    [hView addSubview:deleteButton];
    //编辑
    UIButton *editButton = [UIButton new];
    [editButton setImage:[UIImage imageNamed:@"icon_重命名_24_line备份"] forState:UIControlStateNormal];
    [editButton addTarget:self action:@selector(editorAction:) forControlEvents:UIControlEventTouchUpInside];
    [hView addSubview:editButton];
    
    UIButton *playButton = [UIButton new];
    if (self.chooseType) {
        [playButton setImage:[UIImage imageNamed:@"zhengque"] forState:UIControlStateNormal];
    } else {
        [playButton setImage:[UIImage imageNamed:@"icon_播放_32_defaults"] forState:UIControlStateNormal];
    }
    playButton.hidden = YES;
    if (([isSelect isEqual:@1] && list.count != 0) || ([isSelect isEqual:@1] && self.chooseType)) {
        playButton.hidden = NO;
    }
//    [playButton addTarget:self action:@selector(playAction:) forControlEvents:UIControlEventTouchUpInside];
    [hView addSubview:playButton];

    [vline mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(hView).offset(35);
        make.top.equalTo(hView).offset(0);
        make.height.mas_equalTo(23);
        make.width.mas_equalTo(1);
    }];
    [aidvline mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(hView).offset(35);
        make.top.equalTo(vline.mas_bottom).offset(0);
        make.height.mas_equalTo(15);
        make.width.mas_equalTo(1);
    }];
    [vline2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(vline.mas_right).offset(20);
        make.top.equalTo(hView).offset(0);
        make.height.mas_equalTo(17);
        make.width.mas_equalTo(1);
    }];
    [aidvline2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(vline.mas_right).offset(20);
        make.top.equalTo(vline2.mas_bottom).offset(0);
        make.height.mas_equalTo(21);
        make.width.mas_equalTo(1);
    }];
    [hline mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(vline2.mas_right).offset(0);
        make.top.equalTo(vline2.mas_bottom).offset(-1);
        make.height.mas_equalTo(1);
        make.width.mas_equalTo(10);
    }];

    [hTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(hline.mas_right).offset(0);
        make.centerY.equalTo(hline);
        make.height.mas_equalTo(18);
//        make.right.equalTo(hView).offset(-20);
    }];
    
    [addButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(hTitle.mas_right).offset(12);
        make.centerY.equalTo(hTitle);
        make.height.width.mas_equalTo(24);
    }];

    [deleteButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(addButton.mas_right).offset(5);
        make.centerY.equalTo(hTitle);
        make.height.width.mas_equalTo(24);

    }];

    [editButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(deleteButton.mas_right).offset(5);
        make.centerY.equalTo(hTitle);
        make.height.width.mas_equalTo(24);
    }];

    [playButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(hView.mas_right).offset(-14);
        make.centerY.equalTo(hline);
        make.height.width.mas_equalTo(50);
    }];

//    aidvline.hidden = NO;
    aidvline2.hidden = NO;
    if (section == self.dataSource.count - 1) {
//        aidvline.hidden = YES;
        aidvline2.hidden = YES;
    }
    
    vline.hidden = NO;
    aidvline.hidden = NO;
    if (self.indexPath.section == self.fdataSource.count - 1) {
        vline.hidden = YES;
        aidvline.hidden = YES;
    }
    
    addButton.hidden = YES;
    deleteButton.hidden = YES;
    editButton.hidden = YES;
    if (self.isEditor == YES) {
        addButton.hidden = NO;
        deleteButton.hidden = NO;
        editButton.hidden = NO;
    }

    return hView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [UIView new];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    LinkerModel *info = self.dataSource[indexPath.section];
    NSMutableArray *array = info.list;

    LinkerModel *tModel = array[indexPath.row];

    if (self.tapThirdLevelBlock != nil && [tModel.isSelect isEqual:@0]) {
        self.tapThirdLevelBlock(self.indexPath.section, indexPath.section, indexPath.row);
    }
}

- (void)tapHeaderView:(UIGestureRecognizer *) sender {
    UIView *hView = sender.view;
    NSInteger index = hView.tag - 1000;

    if (self.tapTwoLevelBlock != nil) {
        self.tapTwoLevelBlock(self.indexPath.section, index);
    }
}

- (void)addAction:(UIButton *) sender {
    UIAlertController *controller = [UIAlertController alertControllerWithTitle:@"创建二级分类" message:nil preferredStyle:UIAlertControllerStyleAlert];
    [controller addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = @"请输入分类名称";
        textField.font = [UIFont systemFontOfSize:16 weight:UIFontWeightRegular];
        textField.textColor = [UIColor blackColor];
    }];

    UIAlertAction *confirm = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UITextField *tf = controller.textFields.firstObject;
        if (tf.text.length != 0) {
            LinkerModel *obj2 = [LinkerModel new];
            obj2.type = @2;
            obj2.name = tf.text;

            [self.dataSource addObject:obj2];

            if (self.editorBlock != nil) {
                self.editorBlock();
            }
        }
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {

    }];
    [controller addAction:cancel];
    [controller addAction:confirm];
    [[UIViewController currentViewController] presentViewController:controller animated:YES completion:nil];
}
- (void)deleteAction:(UIButton *) sender {
    NSInteger index = sender.superview.tag - 1000;

    NSString *name = self.dataSource[index].name;

    if (self.dataSource.count == 1) {
        UIAlertAction *delete = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

        }];
        UIAlertController *controller = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"至少保留一个二级分类" preferredStyle:UIAlertControllerStyleAlert];
        [controller addAction:delete];
        [[UIViewController currentViewController] presentViewController:controller animated:YES completion:nil];
        return;
    }

    UIAlertAction *delete = [UIAlertAction actionWithTitle:@"删除" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self.dataSource removeObjectAtIndex:index];
        if (self.editorBlock != nil) {
            self.editorBlock();
        }
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {

    }];

    UIAlertController *controller = [UIAlertController alertControllerWithTitle:@"温馨提示" message:[NSString stringWithFormat:@"您确定要删除%@吗?", name] preferredStyle:UIAlertControllerStyleAlert];
    [controller addAction:cancel];
    [controller addAction:delete];

    [[UIViewController currentViewController] presentViewController:controller animated:YES completion:nil];
}
- (void)editorAction:(UIButton *) sender {
    NSInteger index = sender.superview.tag - 1000;

    UIAlertController *controller = [UIAlertController alertControllerWithTitle:@"修改分类名称" message:nil preferredStyle:UIAlertControllerStyleAlert];
    [controller addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = @"请输入名称";
        textField.font = [UIFont systemFontOfSize:16 weight:UIFontWeightRegular];
        textField.textColor = [UIColor blackColor];
    }];

    UIAlertAction *confirm = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UITextField *tf = controller.textFields.firstObject;
        if (tf.text.length != 0) {
            self.dataSource[index].name = tf.text;
            [self.tableView reloadData];
        }
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {

    }];
    [controller addAction:cancel];
    [controller addAction:confirm];
    
    [[UIViewController currentViewController] presentViewController:controller animated:YES completion:nil];
}
@end
